package config

import "strings"

type Mysql struct {
	DsnType      dsnType `mapstructure:"dsn" json:"dsn" yaml:"dsn"`
	MaxIdleConns int     `mapstructure:"max-idle-conns" json:"max-idle-conns" yaml:"max-idle-conns"` // 空闲中的最大连接数
	MaxOpenConns int     `mapstructure:"max-open-conns" json:"max-open-conns" yaml:"max-open-conns"` // 打开到数据库的最大连接数
}

type dsnType struct {
	Sources  string `mapstructure:"sources" json:"sources" yaml:"sources"`
	Replicas string `mapstructure:"replicas" json:"replicas" yaml:"replicas"`
}

func (m *Mysql) SourcesLen() int {
	return len(strings.Split(m.DsnType.Sources, ","))
}

func (m *Mysql) ReplicasLen() int {
	return len(strings.Split(m.DsnType.Sources, ","))
}

func (m *Mysql) SourceDsn(i int) string {
	return m.Dsn("source", i)
}

func (m *Mysql) ReplicaDsn(i int) string {
	return m.Dsn("replica", i)
}

func (m *Mysql) Dsn(t string, i int) string {
	if t == "source" {
		hosts := strings.Split(m.DsnType.Sources, ",")
		if len(hosts)-1 < i {
			panic("mysql sources host config error")
		}
		return hosts[i]
	}

	hosts := strings.Split(m.DsnType.Replicas, ",")
	if len(hosts)-1 < i {
		panic("mysql replicas host config error")
	}
	return hosts[i]
}

func (m *Mysql) EnabledReplicas() bool {
	return len(m.DsnType.Replicas) == 0
}
